package com.ys.controller.web.purchase;

import com.ys.config.MenuId;
import com.ys.dto.SubGridConfigDto;
import com.ys.entity.purchase.TcgPurchaseOrderPay;
import com.ys.enume.purchase.TcgPurchaseByOrderEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.util.ToolUtil;
import com.ys.vo.W;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采购付款
 */
@Controller
@RequestMapping("/web/purchase/tcgPurchaseOrderPay")
public class WebTcgPurchaseOrderPayController {
	private static final Logger logger = LoggerFactory.getLogger(WebTcgPurchaseOrderPayController.class);

	@Autowired
	private CommonApiService<TcgPurchaseOrderPay> commonApiService;

    private final Long MENU_ID = MenuId.TCG_PurchaseOrderPay;

    private int maxPayNum = 30;//一次支付最大订单数

    /*
     * 采购付款时，弹窗选择付款方式页面
     */
    @GetMapping("/toEditByPay")
    public String toEditByPay(Model model, HttpServletRequest request, HttpServletResponse response, String goodsIds) {
        try {
            Map<String, Object> extraParam = new HashMap<>();


            //获取可以进行付款的状态
            List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getPayStatus();
            //拼接
            String orders = TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList);

            //过滤，只有付款失败和订单待付款的，才可进行付款
            List<Map<String, Object>> groupsByList = new TcgPurchaseOrderPay()
                    .where("A.PurchasePlanGoodsId IN ("+goodsIds+")")
                    .addLeftJoin("TCG_PurchaseByOrder B ON A.PurchaseOrderBid = B.Bid")
                    .addField("B.OrderAmount AS orderAmount")//实际订单金额（含运）
                    .addField("B.AliOrderNumber AS aliOrderNumber")//1688订单号
                    .where("B.OrderStatus IN ("+orders+")")
                    .queryMap();

            BigDecimal orderAmountTotal = BigDecimal.ZERO;
            String payIds = "";
            String goodsIdsByNew = "";
            int payNumOld = 0;
            if(groupsByList!=null && groupsByList.size()>0){
                //去重
                List<Map<String, Object>> resListByGroups = ToolUtil.groupsByList(groupsByList, e->e.get("id").toString());
                payNumOld = resListByGroups.size();
                //大于30
                if(resListByGroups.size()>maxPayNum){
                    //截取前30条数据
                    resListByGroups = resListByGroups.stream().limit(maxPayNum).collect(Collectors.toList());
                }
                for(Map<String, Object> item:resListByGroups){
                    orderAmountTotal = orderAmountTotal.add(new BigDecimal(item.get("orderAmount").toString()));
                    if("".equals(payIds)){
                        payIds = item.get("id").toString();
                    }else {
                        payIds += ","+item.get("id").toString();
                    }
                    if("".equals(goodsIdsByNew)){
                        goodsIdsByNew = item.get("purchasePlanGoodsId").toString();
                    }else {
                        goodsIdsByNew += ","+item.get("purchasePlanGoodsId").toString();
                    }
                }

                int chooseNum = goodsIds.split(",").length;//选择的数量
                int payNum = payIds.split(",").length;//支付的订单数量
                String numTip = "本次一共选择"+chooseNum+"条数据，其中"+payNumOld+"条可支付的订单，本次支付"+payNum+"条订单"+(payNumOld>maxPayNum?"【一次最多支付"+maxPayNum+"条订单】":"");

                extraParam.put("payIds",payIds);
                extraParam.put("goodsIds",goodsIdsByNew);
                extraParam.put("tipInfo","本次支付总金额："+orderAmountTotal+"；");
                extraParam.put("payType",1);
                extraParam.put("vid","ZHBM00001");
                extraParam.put("vyhzhmc","问前集团控股有限公司/CNH");
                extraParam.put("vyhzh","2120120239008552");
                extraParam.put("vkhh","WorldFirst");

                // 子列表配置信息
                SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MENU_ID,resListByGroups);
                commonApiService.toEdit(model,Long.parseLong(groupsByList.get(0).get("id").toString()), new TcgPurchaseOrderPay(), MENU_ID, extraParam, subGridConfig);
                return "purchase/tcgPurchaseOrderPay/toEdit";

            }else {
                return W.error(model, "所选择的付款单均已付款");
            }
        }catch (Exception e) {
            logger.error("详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }




}






